"""
Author: Yishang
Description: 对于浙江人民政府分站意见征集的检查
"""
import re
import logging
from io import BytesIO

from bs4 import BeautifulSoup
from datetime import datetime

from utils import filechecker
from .model import ProcessResult, WebParser


class MinyizjParser(WebParser):
    regex_url = r"[https|http]://minyi\.zjzwfw\.gov\.cn.*dczjnewls\/dczj\/idea.*"

    def __init__(self, *args, **kwargs):
        """
        浙江人民政府分站意见征集处理
        """
        super().__init__(*args, **kwargs)
        return

    def process(self):
        """
        开始自动处理

        :return:
        """
        result = []

        logging.info(f"正在进行自动处理链接 {self.url} ......")

        match = re.search(r".*dczjnewls\/dczj\/idea.*", self.url)
        if match:
            logging.info(f"检测到 {self.url} 属于意见征集页面，正在准备处理。")

            # 是否明确意见征求期限，意见征求期限少于30天的是否说明理由；
            info = self.form_parser()

            print(info)
            return result

        # 没有匹配交给分配
        result += super().process()

        return result

    @staticmethod
    def is_title(style):
        """
        判断是不是标题的特征
        """
        if style is None:
            return False
        styles = dict([item.split(":") for item in style.split(";") if item])
        font_size = int(styles.get("font-size", "0px").replace("px", ""))
        return font_size >= 24 and styles.get("font-weight", "") == "bold"

    def form_parser(self):
        """
        意见征集页面就是一个超大的表单。

        :return:
        """

        if self.response is None:
            self.response = self.session.get(self.url)

        info = {}

        soup = BeautifulSoup(self.response.content.decode(), "lxml")

        form = soup.find('form')

        elements = form.find_all(['td', 'li'])

        # 遍历元素，使用关键词来识别字段并提取内容
        for element in elements:
            text = element.get_text().strip().replace(':', '：')
            text = text[:text.find('\t')]
            if "征集部门" in text:
                info["征集部门"] = text.split("：")[-1].strip()
            elif "发布日期" in text:
                info["发布日期"] = datetime.strptime(text.split("：")[-1].strip(), "%Y-%m-%d")
            elif "截止日期" in text:
                info["截止日期"] = datetime.strptime(text.split("：")[-1].strip(), "%Y-%m-%d")
            elif "发布时间" in text:
                info["发布时间"] = datetime.strptime(text.split("：")[-1].strip(), "%Y-%m-%d")
            elif "信息来源" in text:
                info["信息来源"] = text.split("：")[-1].strip()

        # 很逆天，全部放在 Table 里
        for i, td in enumerate(form.find_all('td', style=self.is_title)):
            # 特征定位
            if i == 0:
                info['征求意见标题'] = td.get_text(strip=True)

                _ = td.find_parent("table").find_next_sibling("table")
                if _ is None:
                    continue

                info['征求意见正文'] = ''
                for p in td.find_parent("table").find_next_sibling("table").find_all("p"):
                    if p.find('a') is not None and 'upload' in p.find('a').attrs.get('href', ''):
                        continue
                    info['征求意见正文'] += p.get_text(strip=True)
            elif i == 1:
                info['截止通知标题'] = td.get_text(strip=True)

                _ = td.find_parent("table").find_next_sibling("table")
                if _ is None:
                    continue
                info['征求意见标题'] = ''

                for p in _.find_all("p"):
                    if p.find('a') is not None and 'upload' in p.find('a').attrs.get('href', ''):
                        continue
                    info['征求意见标题'] += p.get_text(strip=True)

                # match i:
            #     case 0:  # 建议征集原文标题
            #         info['征求意见标题'] = table.find('td').get_text(strip=True)
            #         for li in table.find('tr', class_='pc_ly').find('ul').find_all('li'):
            #             text = li.get_text(strip=True).split('：')
            #
            #             if len(text) == 1:
            #                 continue
            #
            #             if '时间' in text[0]:
            #                 info[text[0]] = datetime.strptime(''.join(text[1:]), "%Y-%m-%d")
            #             else:
            #                 info[text[0]] = ''.join(text[1:])
            #     case 1:  # 意见正文
            #         info['征求意见正文'] = ''
            #         for p in table.find_all('p'):
            #             if p.find('a') is not None and 'upload' in p.find('a').attrs.get('href', ''):
            #                 continue
            #             info['征求意见正文'] += p.get_text(strip=True)
            #     case 2:  # 起止时间
            #         for td in table.find_all('td'):
            #             text = td.get_text(strip=True).split('：')
            #
            #             if len(text) == 1:
            #                 continue
            #
            #             if '时间' in text[0]:
            #                 info[text[0]] = datetime.strptime(''.join(text[1:]), "%Y-%m-%d")
            #             else:
            #                 info[text[0]] = ''.join(text[1:])
            #     case 3:  # 截止公告标题
            #         info['截止通知标题'] = table.get_text(strip=True)

        info['截止通知内容'] = form.find('div', id='jsts').get_text(strip=True)

        return info
